package com.itszt.manager.service.impl;

import com.itszt.common.EasyUIPageDatasBean;
import com.itszt.common.GoodsMsg;
import com.itszt.manager.dao.ITbItemDao;
import com.itszt.manager.dao.ITbItemDescDao;
import com.itszt.manager.service.GoodsService;
import com.itszt.pojo.TbItem;
import com.itszt.pojo.TbItemDesc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private ITbItemDao tbItemDao;

    @Autowired
    private ITbItemDescDao tbItemDescDao;

    @Override
    public List<TbItem> getAllGoods() {
        return tbItemDao.findAll();
    }

    @Override
    public EasyUIPageDatasBean<TbItem> getPageGoods(Integer pageNow, Integer pageCapacity) {
        PageRequest pageBean = PageRequest.of(pageNow, pageCapacity);


        Page<TbItem> tbItemPage = tbItemDao.findAll(pageBean);

        long total = tbItemPage.getTotalElements();
        List<TbItem> list = tbItemPage.getContent();

        EasyUIPageDatasBean<TbItem> easyUIPageDatasBean=new EasyUIPageDatasBean<>();
        easyUIPageDatasBean.setRows(list);
        easyUIPageDatasBean.setTotal(total);

        return easyUIPageDatasBean;
    }

    @Override
    @Transactional
    public boolean addGoods(TbItem item, String desc) throws Exception {

        item.setStatus( 0);
        item.setUpdated(new Date());
        item.setCreated(new Date());

        item = tbItemDao.save(item);

        TbItemDesc tbItemDesc=new TbItemDesc();
        tbItemDesc.setCreated(new Date());
        tbItemDesc.setUpdated(new Date());
        tbItemDesc.setItemDesc(desc);
        tbItemDesc.setItemId(item.getId());

        tbItemDescDao.save(tbItemDesc);


        GoodsMsg goodsMsg=new GoodsMsg();
        goodsMsg.setOpt("add");
        goodsMsg.setTbItemNew(item);

        return true;
    }

    @Override
    public TbItem getGoodsDetail(Long goodsid) {
        return tbItemDao.findById(goodsid).get();
    }

    @Override
    public TbItemDesc getGoodsDesc(Long goodsid) {
        return tbItemDescDao.findByItemId(goodsid);
    }

}
